Rust一面
18 人赞同了该文章
实际讲解你做过的项目,和代码进行分析
我选择讲解以下的 MiniTokio
use futures::task;
use std::collections::VecDeque;
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::{Duration, Instant};
struct Delay {
when: Instant,
}
impl Future for Delay {
type Output = &'static str;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<&'static str> {
if Instant::now() >= self.when {
println!("hello world");
Poll::Ready("done")
} else {
cx.waker().wake_by_ref();
Poll::Pending
}
}
}
struct MiniTokio {
tasks: VecDeque<Task>,
}
//允许将任何实现了 Future Trait 的具体类型(如 async { ... } 块或 Delay)放入同一个队列中
type Task = Pin<Box<dyn Future<Output = ()> + Send>>;
impl MiniTokio {
fn new() -> MiniTokio {
MiniTokio {
tasks: VecDeque::new(),
}
}
/// 生成一个 Future并放入 mini-tokio 实例的任务队列中
fn spawn<F>(&mut self, future: F)
where
F: Future<Output = ()> + Send + 'static,
//Future<Output = ()>: 必须是一个返回 () 的 Future.
{
self.tasks.push_backpin(future);
}
fn run(&mut self) {
let waker = task::noop_waker();
let mut cx = Context::from_waker(&waker);
//取出任务
while let Some(mut task) = self.tasks.pop_front() {
//轮询任务 如果没有完成 把它从后面放回队列
if task.as_mut().poll(&mut cx).is_pending() {
self.tasks.push_back(task);
}
}
}
}
fn main() {
let mut mini_tokio = MiniTokio::new();
mini_tokio.spawn(async {
let when = Instant::now() + Duration::from_millis(10);
let future = Delay { when };
let out = future.await;
assert_eq!(out, "done");
});
mini_tokio.run();
}
问题
- 讲解这段代码的功能然后逐个讲解每一个部分的实现
- 这里怎么体现 异步 的基本原理?
impl和dyn是什么,区别是什么- 已经有了
Box这里为什么要使用Pin - 回答不上来的问题:为什么rust选择了async/await 不是
epoll,io_uring
发布于 2025-09-27 22:00・湖南阿里千问AI,办公提效小助手
[
基于Qwen大模型,千问PC端适配多场景,支持文档处理、翻译、PPT生成等。多窗口同步操作,智能升级无门槛,工...